#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>

struct ListNode* removeNthFromEnd(struct ListNode* head, int n)
{
    // write code here
    if (head == NULL)
        return NULL;

    struct ListNode* cur = head;
    int len = 0;
    while (cur)
    {
        len++;
        cur = cur->next;
    }

    int ret = len - n;
    if (ret == 0)
    {
        struct ListNode* next = head->next;
        free(head);
        return next;
    }
    else
    {
        cur = head;
        struct ListNode* prve = NULL;
        while (ret--)
        {
            prve = cur;
            cur = cur->next;
        }
        prve->next = cur->next;
        free(cur);
        return head;
    }

    return head;
}